package com.huatai.bpmn.utils;


import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.huatai.common.util.StringUtil;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author: nzj
 * @Description:
 * @DateTime: 2023/8/17 17:04
 **/
@Component
public class SqlUtil {

	/**
	 * 拼接sql语句并进行添加
	 * @param tableName
	 * @param insertKeys
	 * @param insertValues
	 */
	public void getInsertSql(String tableName, List<Object> insertKeys, List<Object> insertValues) {
		if (insertKeys.size() != insertValues.size()){
			throw new RuntimeException("字段与数据不匹配");
		}
		String resultKeys = getInsertKeys(insertKeys);
		String insertValue = getInserValue(insertValues);
		String insertSql = " INSERT INTO " +tableName + " " + resultKeys +" VALUES " + insertValue;
		SqlRunner.db().insert(insertSql);
	}

	private String getInserValue(List<Object> insertValues) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("(");
		for (Object insertValue : insertValues) {
			stringBuilder.append("'").append(insertValue).append("'").append(",");
		}
		String resultResult = stringBuilder.substring(0, stringBuilder.length() - 1);
		resultResult+=")";
		return resultResult;
	}

	/**
	 * 获取sql的key和value值
	 * @param keyOrValue
	 * @return
	 */
	private String getInsertKeys(List<Object> keyOrValue) {
		StringBuilder stringBuilder = new StringBuilder();
		stringBuilder.append("(");
		for (Object column : keyOrValue) {
			stringBuilder.append(column).append(",");
		}
		String resultKeys = stringBuilder.substring(0, stringBuilder.length() - 1);
		resultKeys+=")";
		return resultKeys;
	}

	/**
	 * 校验sql是否为查询sql
	 * @param selectSql
	 * @return
	 */
	public static boolean checkQuerySql(String selectSql){
		return StringUtil.containsAnyIgnoreCase(selectSql,"INSERT","INTO","UPDATE","DELETE");
	}
}
